package com.ivory.valley.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.web.servlet.ModelAndView;

import com.ivory.valley.common.IvoryValley;
import com.ivory.valley.common.Resp;

import net.sf.json.JSONObject;


public class HttpUtil {

	public static Map<String, Object> getRequestParam(ServletRequest request) {
		Map<String, Object> param = new HashMap<String, Object>();
		Enumeration<String> e = request.getParameterNames();
		String k;
		String[] v;
		while (e.hasMoreElements()) {
			k = e.nextElement();
			v = request.getParameterValues(k);
			if (v.length == 1) {
				param.put(k, v[0]);
			} else {
				param.put(k, Arrays.asList(v));
			}
		}
		return param;
	}

	public static void outRespJson(HttpServletResponse response, Resp<?> resp) {
		response.setContentType("text/json;UTF-8");
		response.setCharacterEncoding("UTF-8");
		try {
			BeanUtil.bean2Json(response.getOutputStream(), resp);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public static String getRemoteClientIP(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	public static ModelAndView createModelAndView(Resp<?> resp) {
		ModelAndView mav = new ModelAndView();
		if (resp != null) {
			mav.addObject(IvoryValley.AttrName.RESP, resp);
		}
		return mav;
	}

	public static String getBasePath(HttpServletRequest request) {
		return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
				+ request.getContextPath() + "/";
	}
	
	public static String  http_get(String url ){
		String message = "";
		try {
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET");
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			message = new String(jsonBytes,"UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return message;
		
	}
	
	public static String  http_post(String url ){
		String message = "";
		try {
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("POST");
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			message = new String(jsonBytes,"UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return message;
		
	}
	public static String http_post(String url, List<NameValuePair> nvps) throws IOException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpPost httpPost = new HttpPost(url);
			httpPost.setHeader("Accept", "*/*");
			httpPost.setHeader("Accept-Language", "zh-cn");
			httpPost.setHeader("Cache-Control", "no-cache");
			httpPost.setHeader("Accept-Charset", "UTF-8;");

			httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

			CloseableHttpResponse response1 = httpclient.execute(httpPost);
			response1.addHeader("content-type", "application/json");
			response1.addHeader("accept", "application/json");

			try {
				HttpEntity entity1 = response1.getEntity();
				String retStr = null;
				if (entity1 != null) {
					retStr = EntityUtils.toString(entity1);
				}
				return retStr;
			} finally {
				response1.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
			// logger.error(e.getMessage(), e);
		} finally {
			httpclient.close();
		}
		return null;
	}

	public static String https_post(String url, List<NameValuePair> nvps) throws IOException {
		HttpEntity entity = null;
		CloseableHttpResponse response = null;
		try {

			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
			// 执行get请求.
			response = createSSLClient().execute(httpPost);

			// 获取响应实体
			entity = response.getEntity();
			String retStr = null;
			if (entity != null) {
				retStr = EntityUtils.toString(entity);
			}
			return retStr;

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (entity != null) {
				try {
					entity.getContent().close();
				} catch (UnsupportedOperationException | IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return "";
	}

	public static CloseableHttpClient createSSLClient() {
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				// 信任所有
				@Override
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}
			}).build();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
					SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			return HttpClients.custom().setSSLSocketFactory(sslsf).build();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return HttpClients.createDefault();
	}
}